package com.prj.controller;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.prj.entity.TM;
import com.prj.entity.TMSJ;
import com.prj.service.TMService;

import cn.hutool.core.io.IoUtil;

@Controller
public class TMController {
	
	@Autowired
	private TMService service;
	
	
	@GetMapping("/")
	public String index() {
		return "index";
	}
	
	@GetMapping("/page/{page}")
	public String page(@PathVariable("page") String page) {
		if("cust_mobile".equals(page)) {
			return "cust";
		}
		return page;
	}
	
	@RequestMapping("/pdf")
	public void viewFile(HttpServletResponse response) throws Exception {
		response.setContentType("application/pdf");
		InputStream in = this.getClass().getClassLoader().getResourceAsStream("广东省健康管理师考前复习.pdf");
		IoUtil.copy(in, response.getOutputStream());
	}
	
	
	/**
	 * http://localhost:18500/genOrderSJ
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/genOrderSJ")
    public void genOrderSJ(HttpServletResponse response, Integer type) throws Exception{
        byte[] bytes = service.genSJ(type).getBytes(StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition","attachement; fileName="+URLEncoder.encode("健康管理师.txt", StandardCharsets.UTF_8.displayName()));
        OutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
    }
	
	/**
	 * http://localhost:18500/randgenSJ?dls=J1&type=J&tkType=1&num=
	 * @param response
	 * @param tm
	 * @throws Exception
	 */
	@RequestMapping("/randgenSJ")
    public void genSJ(HttpServletResponse response, TM tm) throws Exception{
        byte[] bytes = service.randgenSJ(tm).getBytes(StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition","attachement; fileName="+URLEncoder.encode(tm.getFileName()+".txt", StandardCharsets.UTF_8.displayName()));
        OutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
    }
	
	/**
	 * http://localhost:18500/downError?type=1
	 * @param response
	 * @param tm
	 * @throws Exception
	 */
	@RequestMapping("/downError")
    public void downError(HttpServletResponse response, TMSJ sj) throws Exception{
        byte[] bytes = service.downError(sj).getBytes(StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition","attachement; fileName="+URLEncoder.encode("错题.txt", StandardCharsets.UTF_8.displayName()));
        OutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
    }

}
